<?php

namespace app\admin\model;
use think\exception\PDOException;
use think\Model;

class OptionCatModel extends Model
{
    protected $name = 'option_cat';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;


    /**
     * 根据搜索条件获取轮播列表信息
     */
    public function getCatByWhere($map, $Nowpage, $limits)
    {
        return $this->field('*')->where($map)->page($Nowpage, $limits)->order('sort asc')->select();
    }

    public function upShow($type)
    {
        $a = $type == 1 ? 1 : -1;
        $b = $type == 1 ? -1 : 1;
        $this->where('is_show',$b)->update(['is_show'=>$a]);
        return ['code' => 1, 'data' => '', 'msg' => '下架成功'];
    }



    /**
     * params $param
     * @author felix
     */
    public function insertCat($param)
    {
        try{
            $result = $this->allowField(true)->save($param);
            if(false === $result){
                return ['code' => -1, 'data' => '', 'msg' => $this->getError()];
            }else{
                return ['code' => 1, 'data' => '', 'msg' => '添加成功'];
            }
        }catch( PDOException $e){
            return ['code' => -2, 'data' => '', 'msg' => $e->getMessage()];
        }
    }


    /**
     * @author felix
     */
    public function updateCat($param)
    {
        try{
            $result = $this->allowField(true)->save($param, ['id' => $param['id']]);
            if(false === $result){
                return ['code' => 0, 'data' => '', 'msg' => $this->getError()];
            }else{
                return ['code' => 1, 'data' => '', 'msg' => '编辑成功'];
            }
        }catch( PDOException $e){
            return ['code' => 0, 'data' => '', 'msg' => $e->getMessage()];
        }
    }



    /**
     * @author felix
     */
    public function getOneCat($id)
    {
        return $this->where('id', $id)->find();
    }



    /**
     * @author felix
     */
    public function delCat($id)
    {
        try{
            $r = db('option')->where('cat_id',$id)->find();
            if($r) return ['code' => 0, 'data' => '', 'msg' => '有关联标签存在！'];
            $this->where('id', $id)->delete();
            return ['code' => 1, 'data' => '', 'msg' => '删除成功'];
        }catch( PDOException $e){
            return ['code' => 0, 'data' => '', 'msg' => $e->getMessage()];
        }
    }


}